//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.example.demo.utils;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class JBlowfish {
    private static final String ALGORATM = "Blowfish";
    private static final String ALGORATMD = "Blowfish/CBC/PKCS5Padding";
    private static final String ENCODING = "UTF-8";

    private JBlowfish() {
    }

    public static byte[] encrypt(byte[] data, String password, String iv) throws GeneralSecurityException, NoSuchPaddingException {
        SecretKeySpec keySpec = new SecretKeySpec(getKey(password), "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
        cipher.init(1, keySpec, new IvParameterSpec(getIV(iv)));
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] data, String password, String iv) throws GeneralSecurityException, NoSuchPaddingException {
        SecretKeySpec keySpec = new SecretKeySpec(getKey(password), "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
        cipher.init(2, keySpec, new IvParameterSpec(getIV(iv)));
        return cipher.doFinal(data);
    }

    public static String encrypt(String plainText, String password, String iv) throws GeneralSecurityException, UnsupportedEncodingException {
        byte[] data = encrypt(plainText.getBytes("UTF-8"), password, iv);

        return new String(Base64.getEncoder().encode(data));
    }

    public static String decrypt(String cipherText, String password, String iv) throws GeneralSecurityException, UnsupportedEncodingException {
        byte[] data = decrypt(Base64.getDecoder().decode(cipherText), password, iv);
        return new String(data, "UTF-8");
    }

    private static byte[] getKey(String password) {
        return subKey(password, 16);
    }

    private static byte[] getIV(String iv) {
        return subKey(iv, 8);
    }

    private static byte[] subKey(String key, int size) {
        String subKey = key;
        if (key.length() > size) {
            subKey = key.substring(0, size);
        } else if (key.length() < size) {
            int count = size - key.length();

            for(int i = 0; i < count; ++i) {
                subKey = subKey + "0";
            }
        }

        return subKey.getBytes();
    }
}
